package com.mxnet.chongjin.nci.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mxnet.chongjin.nci.R;
import com.mxnet.chongjin.nci.base.BaseActivity;
import com.mxnet.chongjin.nci.bean.Inspection;
import com.mxnet.chongjin.nci.config.Api;
import com.mxnet.chongjin.nci.receiver.HoneywellReceiver;
import com.mxnet.chongjin.nci.utils.StringUtils;
import com.mxnet.chongjin.nci.view.ItemStockCheckView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class StockCheckActivity extends BaseActivity implements HoneywellReceiver.OnReceiveCode {
    private Context mContext;
    private Button mButtonQuit, mButtonClear, mButtonSure;
    private TextView mTextViewScanResult, mTextViewBarcode, mTextViewLot, mTextViewCheckqty, mTextViewInqty;
    private LinearLayout mLayout;
    private SharedPreferences mPreferences;
    private List<Inspection> mInspectionList;
    private int inqtySum, checkqtySum;
    private List<ItemStockCheckView> mViewList;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    inqtySum = 0;
                    for (ItemStockCheckView inspectionView : mViewList) {
                        if (!TextUtils.isEmpty(inspectionView.getEditText().getText().toString())) {
                            inqtySum += Integer.parseInt(inspectionView.getEditText().getText().toString());
                        }
                    }
                    mTextViewInqty.setText(inqtySum + "");
                    break;
            }
        }
    };

    private HoneywellReceiver mHoneywellReceiver = new HoneywellReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            if ((HoneywellReceiver.INTENT_SCAN_ACTION).equals(intent.getAction())) {
                final String data = StringUtils.replaceBlank(intent.getStringExtra("data"));
                if (!TextUtils.isEmpty(data)) {
                    mTextViewScanResult.setText("扫描成功");
                    mTextViewScanResult.setTextColor(Color.GREEN);
                    if (data.length() == 8) {
                        // 长度为6表示是库位,长度为8表示卷号
                        mTextViewBarcode.setText(data);
                    }
                } else {
                    mTextViewScanResult.setText("扫描异常");
                    mTextViewScanResult.setTextColor(Color.RED);
                }
            }
        }
    };

    @Override
    public void notifyThread(Intent intent) {
        final String data = StringUtils.replaceBlank(intent.getStringExtra("data"));
        if (data.length() == 8) {
            OkHttpUtils.get()
                    .url(mPreferences.getString("URL_HEADER", "") + Api.BARCODE_QUERY_INSPECTION)
                    .addParams("barcode", data)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.i("*****==onError==", e.getMessage());
                            mTextViewScanResult.setText(e.getMessage());
                            mTextViewScanResult.setTextColor(Color.RED);
                            mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.i("*****test", response);
                            if (!TextUtils.isEmpty(response)) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    boolean isSuccess = jsonObject.optBoolean("success");
                                    if (isSuccess) {
                                        mInspectionList.clear();
                                        inqtySum = 0;
                                        checkqtySum = 0;
                                        JSONArray datas = jsonObject.optJSONArray("data");
                                        String lotStr = "";
                                        if (datas != null && datas.length() > 0)
                                            lotStr = datas.getJSONObject(0).getString("lot");
                                        final String lot = lotStr;
                                        mTextViewLot.setText(lot);
                                        for (int i = 0; i < datas.length(); i++) {
                                            Inspection inspection = new Inspection();
                                            inspection.setLot(lot);
                                            inspection.setLocationCode(datas.optJSONObject(i).optString("location"));
                                            inspection.setInQty(datas.optJSONObject(i).optInt("inqty"));
                                            mInspectionList.add(inspection);
                                            checkqtySum += StringUtils.toInt(datas.optJSONObject(i), "inqty");
                                            ;

                                            inqtySum += StringUtils.toInt(datas.optJSONObject(i), "checkqty");
                                            ;
                                            ItemStockCheckView itemStockCheckView = new ItemStockCheckView(mContext, R.layout.item_stock_check);
                                            itemStockCheckView.getTextView1().setText(lot);
                                            itemStockCheckView.getTextView2().setText(datas.optJSONObject(i).optString("location"));

                                            itemStockCheckView.getTextView3().setText(StringUtils.toInt(datas.optJSONObject(i), "checkqty") + "");
                                            itemStockCheckView.getTextView3().setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    Intent intent = new Intent(mContext, ReportActivity.class);
                                                    intent.putExtra("lot", SpannableString.valueOf(lot));
                                                    startActivity(intent);
                                                }
                                            });
                                            itemStockCheckView.getEditText().setText(StringUtils.toInt(datas.optJSONObject(i), "inqty") + "");
                                            itemStockCheckView.getEditText().addTextChangedListener(new TextWatcher() {
                                                @Override
                                                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                                }

                                                @Override
                                                public void onTextChanged(CharSequence s, int start, int before, int count) {

                                                }

                                                @Override
                                                public void afterTextChanged(Editable s) {
                                                    Message message = Message.obtain();
                                                    message.what = 1;
                                                    mHandler.sendMessage(message);
                                                }
                                            });
                                            mViewList.add(itemStockCheckView);
                                            mLayout.addView(itemStockCheckView, 0);
                                        }
                                        mTextViewCheckqty.setText(checkqtySum + "");
                                        mTextViewInqty.setText(inqtySum + "");
                                    } else {
                                        mTextViewScanResult.setText(jsonObject.optString("message"));
                                        mTextViewScanResult.setTextColor(Color.RED);
                                        mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mHoneywellReceiver, new IntentFilter(HoneywellReceiver.INTENT_SCAN_ACTION));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory_check);
        mContext = StockCheckActivity.this;
        mPreferences = getPreferences();

        mInspectionList = new ArrayList<>();
        mViewList = new ArrayList<>();

        mHoneywellReceiver.setOnReceiveCode(this);

        mTextViewScanResult = findViewById(R.id.textview_stock_check_scan_result);

        mTextViewBarcode = findViewById(R.id.textview_stock_check_barcode);

        mTextViewLot = findViewById(R.id.textview_stock_check_lot);

        mTextViewCheckqty = findViewById(R.id.textview_stock_check_checkqty);
        mTextViewCheckqty.setText("0");

        mTextViewInqty = findViewById(R.id.textview_stock_check_inqty);
        mTextViewInqty.setText("0");

        mLayout = findViewById(R.id.ll_stock_check_list);

        String str = getIntent().getStringExtra("lot");
        if (!TextUtils.isEmpty(str)) {
            initView();
        }

        mButtonQuit = findViewById(R.id.btn_stock_check_quit);
        mButtonQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, IndexActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        });

        mButtonClear = findViewById(R.id.btn_stock_check_clear);
        mButtonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextViewBarcode.setText("");
                mTextViewCheckqty.setText("");
                mTextViewInqty.setText("");
                mInspectionList.clear();
                mViewList.clear();
                mLayout.removeAllViews();
            }
        });

        mButtonSure = findViewById(R.id.btn_stock_check_sure);
        mButtonSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mInspectionList.size(); i++) {
                    mInspectionList.get(i).setInQty(Integer.parseInt(mViewList.get(i).getEditText().getText().toString()));
                }
                OkHttpUtils.get()
                        .url(mPreferences.getString("URL_HEADER", "") + Api.INSERT_CHECKQTY)
                        .addParams("data", new Gson().toJson(mInspectionList))
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Log.i("*****onError", e.getMessage());
                                mTextViewScanResult.setText(e.getMessage());
                                mTextViewScanResult.setTextColor(Color.RED);
                                mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean isSuccess = jsonObject.optBoolean("success");
                                        if (isSuccess) {
                                            Toast.makeText(mContext, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                        } else {
                                            mTextViewScanResult.setText(jsonObject.optString("message"));
                                            mTextViewScanResult.setTextColor(Color.RED);
                                            mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
            }
        });
    }

    public void initView() {
        String str = getIntent().getStringExtra("lot");
        OkHttpUtils.get()
                .url(mPreferences.getString("URL_HEADER", "") + Api.QUERY_NOT_INSPECTION)
                .addParams("lot", str)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("*****onError", e.getMessage());
                        mTextViewScanResult.setText(e.getMessage());
                        mTextViewScanResult.setTextColor(Color.RED);
                        mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    mInspectionList.clear();
                                    inqtySum = 0;
                                    checkqtySum = 0;
                                    JSONArray datas = jsonObject.optJSONArray("data");
                                    for (int i = 0; i < datas.length(); i++) {
                                        Inspection inspection = new Inspection();
                                        inspection.setId(datas.optJSONObject(i).optInt("id"));
                                        inspection.setLot(datas.optJSONObject(i).optString("lot"));
                                        inspection.setLocationCode(datas.optJSONObject(i).optString("location"));
                                        inspection.setInQty(datas.optJSONObject(i).optInt("inqty"));
                                        mInspectionList.add(inspection);

                                        inqtySum += StringUtils.toInt(datas.optJSONObject(i), "inqty");
                                        checkqtySum += StringUtils.toInt(datas.optJSONObject(i), "checkqty");
                                        ItemStockCheckView itemStockCheckView = new ItemStockCheckView(mContext, R.layout.item_stock_check);
                                        itemStockCheckView.getTextView1().setText(datas.optJSONObject(i).optString("lot"));
                                        itemStockCheckView.getTextView2().setText(datas.optJSONObject(i).optString("location"));
                                        itemStockCheckView.getTextView3().setText(StringUtils.toInt(datas.optJSONObject(i), "checkqty") + "");

                                        itemStockCheckView.getTextView3().setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                ItemStockCheckView itemStockCheckView = (ItemStockCheckView) v.getParent().getParent();
                                                Intent intent = new Intent(mContext, ReportActivity.class);
                                                intent.putExtra("lot", SpannableString.valueOf(itemStockCheckView.getTextView1().getText()));
                                                startActivity(intent);
                                            }
                                        });
                                        itemStockCheckView.getEditText().setText(StringUtils.toInt(datas.optJSONObject(i), "inqty") + "");
                                        itemStockCheckView.getEditText().addTextChangedListener(new TextWatcher() {
                                            @Override
                                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                            }

                                            @Override
                                            public void onTextChanged(CharSequence s, int start, int before, int count) {

                                            }

                                            @Override
                                            public void afterTextChanged(Editable s) {
                                                Message message = Message.obtain();
                                                message.what = 1;
                                                mHandler.sendMessage(message);
                                            }
                                        });
                                        Log.i("*****===", response);
                                        mViewList.add(itemStockCheckView);
                                        mLayout.addView(itemStockCheckView, 0);
                                    }
                                    mTextViewCheckqty.setText(checkqtySum + "");
                                    mTextViewInqty.setText(inqtySum + "");
                                } else {
                                    mTextViewScanResult.setText(jsonObject.optString("message"));
                                    mTextViewScanResult.setTextColor(Color.RED);
                                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mHoneywellReceiver);
    }
}
